package com.aic.aicdetactor.service;

import android.app.ProgressDialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.aic.aicdetactor.CacheControl;
import com.aic.aicdetactor.CustomListAdapter;
import com.aic.aicdetactor.DataRequestThread;
import com.aic.aicdetactor.MainActivity;
import com.aic.aicdetactor.PageControl;
import com.aic.aicdetactor.analysis.CurveValuePair;
import com.aic.aicdetactor.analysis.FFTValuePair;
import com.aic.aicdetactor.analysis.ReceivedDataAnalysis;
import com.aic.aicdetactor.broadcast.Keys;
import com.aic.aicdetactor.common.CommonDef;
import com.aic.aicdetactor.common.Constants;
import com.aic.aicdetactor.common.Setting;
import com.aic.aicdetactor.crash.AICApplication;
import com.aic.aicdetactor.util.HexUtil;
import com.aic.aicdetactor.util.LogUtil;
import com.aic.aicdetactor.util.SystemUtil;
import com.aic.aicdetactor.util.ToastUtil;
import com.aic.xj.app.ble.BluetoothRequest;
import com.aic.xj.app.resource.GBMap;
import com.aic.xj.app.sdk.HandlerConstants;
import com.aic.xj.app.sdk.Sensor;
import com.aic.xj.app.sdk.SensorOperator;
import com.aic.xj.app.util.StringUtil;
import com.aic.xj.data.aicdataanalysis.FreDomainPara;
import com.aicmonitor.aicdetactorsimple.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class AICService extends Service {

    private final static String TOTAL = "com.aicmonitor.aicdetactorsimple.control";
    private final static String SEND_BLUETOOTH_VALUE = "com.aicmonitor.aicdetactorsimple.control.getBluetoothList";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_CONNECT_DEVICE = "com.aicmonitor.aicdetactorsimple.control.connect.device";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS = "com.aicmonitor.aicdetactorsimple.control.bluetooth.status";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_POWER = "com.aicmonitor.aicdetactorsimple.control.bluetooth.power";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_POWERPERCENT = "com.aicmonitor.aicdetactorsimple.control.bluetooth.powerpercent";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_LOWPOWER = "com.aicmonitor.aicdetactorsimple.control.bluetooth.lowpower";

    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_START_STATUS = "com.aicmonitor.aicdetactorsimple.control.start.status";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_STOP_STATUS = "com.aicmonitor.aicdetactorsimple.control.stop.status";


    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_CONNECT_STATUS = "com.aicmonitor.aicdetactorsimple.control.connect.status";

    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_CONNECT = "com.aicmonitor.aicdetactorsimple.control.bluetooth.connect";
    private final static String COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_DISCONNECT = "com.aicmonitor.aicdetactorsimple.control.bluetooth.disconnect";

    private ControlReceiver controlReceiver;

    private Setting setting = null;//2016-11-15 liuhg添加
    private SensorOperator _operator = null;
    private ReceivedDataAnalysis _analysis = null;
    private int mSamplerate = 0;
    private float fashelv = 0.98f;//发射率
    private float jiasudulingmin = 50.1f;//加速度灵敏
    private float sudujiaozhengxishu = 1.06f;//速度矫正系数
    private float weiyijiaozhengxishu = 7.9f;//位移矫正系数
    private float wendujiaozhengxishu = 0.0f;//温度矫正系数
    private Object _lock = new Object();
    private DataRequestThread _requestor = null;
    private String _bluetoothAddress;//记录蓝牙地址
    private int mTimeStartSum = 15000;//2016-11-09 liuhg添加
    private int mTimeConnectOut = 8000;//2016-11-09 liuhg添加
    private int mMaxSamplerate = 2560;
    private BluetoothAdapter mBluetoothAdapter;
    private Context mContext;
    private BlueToothReceiver blueToothReceiver;


    private boolean isBluetoothCloseRun = false;
    private boolean isBluetoothOpeningRun = false;
    private boolean isBluetoothOpenRun = false;
    private boolean isBluetoothCloseingRun = false;

    private boolean isStartStatusRun = false;
    private boolean isStopStatusRun = false;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        //注册广播
        if (controlReceiver == null){
            controlReceiver = new ControlReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(TOTAL);
            //当网络发生变化的时候，系统广播会发出值为android.net.conn.CONNECTIVITY_CHANGE这样的一条广播
            registerReceiver(controlReceiver, intentFilter);
        }

        if (blueToothReceiver == null){
            blueToothReceiver = new BlueToothReceiver();
            IntentFilter intentFilter1 = new IntentFilter();
//            intentFilter1.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
//            intentFilter1.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
//            intentFilter1.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            // 监视蓝牙设备与APP连接的状态
            intentFilter1.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            intentFilter1.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
            registerReceiver(blueToothReceiver,intentFilter1);
        }





        //开启获取值的服务
        startService(new Intent(AICService.this,BroadcastService.class));

        //获取蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        try {
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_AvailableSensor, new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_single_choice, new ArrayList<String>()));
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Log, new CustomListAdapter(getBaseContext(), R.layout.custom_list, new ArrayList<String>()));

            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Temperature, CommonDef.InvalidValue);//2016-11-08 liuhg添加
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Voltage, CommonDef.InvalidValue);//2016-11-08 liuhg添加
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Sensor_Name_Address, "");//2016-11-07 liuhg添加


            setting = new Setting();//此处实例化是为了在开启程序时在SD卡中建立默认文件夹
            _operator = new SensorOperator(_handler, getApplicationContext());

        } catch (Exception e) {
            LogUtil.GetInstance().append(e);
        }

        return super.onStartCommand(intent, flags, startId);
    }


    public class ControlReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
//	    	Toast.makeText(MainActivity.this,action,Toast.LENGTH_SHORT).show();
            switch (action) {
                case TOTAL:
                    boolean isSearchStart = intent.getBooleanExtra("isSearchStart", false);//是否开始搜索
                    boolean isSearchStop = intent.getBooleanExtra("isSearchStop", false);//是否停止搜索
                    boolean isStart = intent.getBooleanExtra("isStart", false);//是否开始采集数据
                    boolean isStop = intent.getBooleanExtra("isStop", false);//是否停止采集数据
                    boolean isChangeName = intent.getBooleanExtra("isChangeName", false);//是否改名
                    boolean isGetConnectDevice = intent.getBooleanExtra("isGetConnectDevice",false);//是否获取当前连接的蓝牙设备
                    boolean isOpenBluetooth = intent.getBooleanExtra("isOpenBluetooth",false);//是否打开蓝牙
                    boolean isCloseBluetooth = intent.getBooleanExtra("isCloseBluetooth",false);//是否关闭蓝牙
                    boolean isGetBluetoothStatus = intent.getBooleanExtra("isGetBluetoothStatus",false);//是否获取蓝牙状态

                    if (isSearchStart) {
                        synchronized (_lock) {
                            if (_requestor != null) {
                                ToastUtil.showToast(getBaseContext(), "正在测量，无法搜索传感器，请先停止测量");
                                return;
                            }
                        }
                        if (!_operator.isDiscovering()) {
//                            ListView lv = (ListView) findViewById(R.id.lv_sensor);
//                            ((ArrayAdapter<String>) lv.getAdapter()).clear();
                            _operator.startDiscovery(15000);
                        } else {
                        }
                    } else if (isSearchStop) {
                        _operator.stopDiscovery();
                    } else if (isStart) {
                        if (_requestor == null) {
                            _operator.stopDiscovery();
                            String sensorname = intent.getStringExtra("name");
                            if (TextUtils.isEmpty(sensorname)) {
                                ToastUtil.showToast(getBaseContext(), "没携带蓝牙名称");
                                return;
                            } else {
                                String address = sensorname.substring(sensorname.indexOf("[") + 1, sensorname.indexOf("]"));
                                _bluetoothAddress = address;
                                List<BluetoothRequest> requests = makeRequests();
                                int interval = 0;

                                float defaulta = jiasudulingmin;
                                float defaultv = sudujiaozhengxishu;
                                float defaultd = weiyijiaozhengxishu;
                                float defaultt = wendujiaozhengxishu;
                                float defaulte = fashelv;
                                try {
                                    if (defaulte < 0.7f || defaulte > 1f) {
                                        addLog("无效数值，发射率范围为0.7~1.0");
                                        return;
                                    }
                                    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(AICApplication.getApplication());
                                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                                    editor.putFloat(CacheControl.Key_Value_Txt_Default_E, defaulte);
                                    editor.commit();
                                    CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_E, defaulte);
                                } catch (Exception ex) {
                                    addLog("五个分析初始值不正确，请正确填写五个浮点数");
                                    return;
                                }
                                _analysis = new ReceivedDataAnalysis(defaulta, defaultv, defaultd, defaultt);
                                _analysis.InputTempPrams(address, 0);
                                _requestor = new DataRequestThread(_operator, address, requests, interval);
                                addLog("开始测量,开始中，请稍后…");
                                boolean flag = false;
                                try {
                                    flag = (Boolean) CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration);
                                } catch (Exception e) {
                                    flag = false;
                                }
                                if (flag) {
                                    mTimeStartSum = 6000;
                                    mTimeConnectOut = 3000;
                                }
                                new Thread() {
                                    @Override
                                    public void run() {
//								if (_requestor.init(15000)) //2016-11-09 liuhg修改前原程序
                                        if (_requestor.init(mTimeStartSum, mTimeConnectOut))//2016-11-09 liuhg修改
                                        {
                                            _requestor.start();
                                            _handler.obtainMessage(Constants.HANDLER_MEASUREMENT_STARTED, 1, 0, null).sendToTarget();
                                        } else {
                                            if (_requestor != null) {
                                                _requestor.cancel();
                                                _requestor = null;
                                            }
                                            _handler.obtainMessage(Constants.HANDLER_MEASUREMENT_STARTED, 0, 0, null).sendToTarget();
                                        }
                                    }
                                }.start();
                            }
                        } else {
                            addLog("正在测量，无法开始，请先停止测量");
                        }
                    }else if (isStop) {
                        stopBluetoothMeasurment("停止中", "正在停止，请稍后……", "已停止测量，可以重新设定参数再次开始测量", 0);
                    }else if (isChangeName) {
                        String sensorname = intent.getStringExtra("name");
                        final String address = sensorname.substring(sensorname.lastIndexOf("[") + 1, sensorname.lastIndexOf("]"));
                        final String newname = intent.getStringExtra("newName");
                        final String encodingname = GBMap.getInstance().encoding(newname);
                        if (encodingname.equals("#ContentTooLong")) {
                            addLog("传感器名字不能为空");
                        } else if (encodingname.equals("#ContentTooLong")) {
                            addLog("传感器名字太长，9个汉字或15个英文字母");
                        } else if (encodingname.equals("#UnsupportChar")) {
                            addLog("仅支持汉字大写字母和#@()，请重取名");
                        } else {
                            addLog("开始改名,改名中，请稍后…");
                            new Thread() {
                                @Override
                                public void run() {
                                    byte[] encodingnamebytes = null;
                                    try {
                                        encodingnamebytes = encodingname.getBytes("ASCII");
                                    } catch (UnsupportedEncodingException e1) {
                                        Log.e("zxh", e1.toString());
                                    }
                                    try {
                                        String result = _operator.open(address, 15000);
                                        if (result.equals("#OK")) {
                                            byte[] data = new byte[]{(byte) 0x7F, (byte) 0x17, (byte) 0xD4, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
                                            for (int i = 0; i < encodingnamebytes.length; i++) {
                                                data[i + 3] = encodingnamebytes[i];
                                            }
                                            byte[] response = _operator.ioControl(0xD4, data, 4000, 20);
                                            if (response != null && response[2] == (byte) 0xD4 && response[3] == (byte) 0x5A) {
                                                _handler.obtainMessage(Constants.HANDLER_IOCONTROL_SETNAME, 1, 0, newname).sendToTarget();
                                            } else {
                                                _handler.obtainMessage(Constants.HANDLER_IOCONTROL_SETNAME, 0, 0, newname).sendToTarget();
                                            }
                                        } else {
                                            _handler.obtainMessage(HandlerConstants.HANDLER_ERROR, 0, 0, "连接失败:" + result).sendToTarget();
                                        }

                                    } catch (Exception e) {
                                        _handler.obtainMessage(HandlerConstants.HANDLER_ERROR, 0, 0, e.getMessage()).sendToTarget();
                                        _handler.obtainMessage(Constants.HANDLER_IOCONTROL_SETNAME, 0, 0, newname).sendToTarget();
                                    } finally {
                                        _operator.close();
                                    }
                                }
                            }.start();
                        }
                    }else if(isGetConnectDevice){
                        Set<BluetoothDevice> bluetoothDeviceSet = mBluetoothAdapter.getBondedDevices();
                        if (bluetoothDeviceSet != null && bluetoothDeviceSet.size() > 0){
                            Iterator<BluetoothDevice> it = bluetoothDeviceSet.iterator();

                            while(it.hasNext()){
                                BluetoothDevice bluetoothDevice = it.next();//取出元素
                                String macAddr = bluetoothDevice.getAddress();
                                if (!TextUtils.isEmpty(macAddr)){
                                    sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_CONNECT_DEVICE).putExtra("name",macAddr));
                                }
                            }
                        }else{
                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_CONNECT_DEVICE).putExtra("name","-1"));
                        }
                    }else if(isOpenBluetooth){
                        mBluetoothAdapter.enable();
                    }else if(isCloseBluetooth){
//                        if (mBluetoothAdapter.enable()){
                            mBluetoothAdapter.disable();
//                        }
                    }else if(isGetBluetoothStatus){
                        int status = mBluetoothAdapter.getState();
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS).putExtra("status",status+""));
//                        if (status == 10 && !isBluetoothCloseRun){//蓝牙已关闭
//                            isBluetoothCloseRun = true;
//                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS).putExtra("status",status+""));
//                        }else if(status == 11 && !isBluetoothOpeningRun){//蓝牙正在打开
//                            isBluetoothOpenRun = true;
//                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS).putExtra("status",status+""));
//                        }else if(status == 12 && !isBluetoothOpenRun){//蓝牙已打开
//                            isBluetoothOpenRun = true;
//                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS).putExtra("status",status+""));
//                        }else if(status == 13 && !isBluetoothCloseingRun){//蓝牙正在关闭
//                            isBluetoothCloseingRun = true;
//                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_STATUS).putExtra("status",status+""));
//                        }




                    }
                    break;
            }
        }
    }

    private final Handler _handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                if (msg.what == Constants.HANDLER_IOCONTROL) {

                    if (msg.obj != null) {
                        if (msg.arg1 == 0xD1) {
                            float[] values = null;
                            float evalue = 0;
                            float highvalue = 0;
                            float highvalue2 = 0;
                            float[] fxs = null;
                            float[] fys = null;
                            FreDomainPara[] fdps = null;
                            String unit = null;

                            double slope = 0;
                            double kurtosis = 0;
                            double wavefactor = 0;
                            double peakfactor = 0;
                            double pulsefactor = 0;
                            double clearancefactor = 0;
                            double kurtosisfactor = 0;
                            DecimalFormat df = new DecimalFormat("#.0000");//保留两位小数
                            synchronized (_analysis) {
                                byte[] data = (byte[]) msg.obj;

                                int result = _analysis.getDataFromBLE(data, (byte) msg.arg1);
                                if (result == 0) {
                                    values = _analysis.getWaveFloatData(mSamplerate);
                                    evalue = _analysis.getValidValue(); //有效值
                                    highvalue = _analysis.getFabsMaxValue(); //峰值
                                    highvalue2 = _analysis.getFengFengValue(); //峰峰值
                                    //2019-02-16 chupengyu start 开启广播传输数据
                                    startSendBroadcast(Keys.EVALUE_ACTION, Keys.eKey, String.valueOf(evalue));
                                    startSendBroadcast(Keys.VIBPEAK_ACTION, Keys.peakKey, String.valueOf(highvalue));
                                    startSendBroadcast(Keys.VIB_PEAK2PEAK_ACTION, Keys.vibPeak2PeakKey, String.valueOf(highvalue2));
                                    //end
                                    slope = Double.parseDouble(df.format(_analysis.GetSlope()));
                                    kurtosis = Double.parseDouble(df.format(_analysis.GetKurtosis()));
                                    wavefactor = Double.parseDouble(df.format(_analysis.GetWaveFactor()));
                                    peakfactor = Double.parseDouble(df.format(_analysis.GetPeakFactor()));
                                    pulsefactor = Double.parseDouble(df.format(_analysis.GetPulseFactor()));
                                    clearancefactor = Double.parseDouble(df.format(_analysis.GetClearanceFactor()));
                                    kurtosisfactor = Double.parseDouble(df.format(_analysis.GetKurtosisFactor()));

                                    fxs = _analysis.getFFTDataArrayX();
                                    fys = _analysis.getFFTDataArrayY();
                                    fdps = _analysis.getMaxFD();
                                    if (data[5] == (byte) 0x01) {
                                        unit = "m/^s";
                                    } else if (data[5] == (byte) 0x02) {
                                        unit = "mm/s";
                                    } else if (data[5] == (byte) 0x03) {
                                        unit = "um";
                                    } else {
                                        unit = "?";
                                    }
                                } else {
                                    addLog("0xD1:" + result);
                                    return;
                                }
                            }

                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Effective, evalue);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_High, highvalue);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_HighHigh, highvalue2);

                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Unit, unit);

                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Amplitude1, fdps[0].M);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Amplitude2, fdps[1].M);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Amplitude3, fdps[2].M);

                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Rate1, fdps[0].Fre);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Rate2, fdps[1].Fre);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Rate3, fdps[2].Fre);

                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Slope, slope);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Kurtosis, kurtosis);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_WaveFactor, wavefactor);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_PeakFactor, peakfactor);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_PulseFactor, pulsefactor);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_ClearanceFactor, clearancefactor);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_KurtosisFactor, kurtosisfactor);


                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Chart_Wave, values);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Chart_FFT, new FFTValuePair(fxs, fys));

                            synchronized (PageControl._lock) {
                                if (PageControl._timeChart != null) {
                                    PageControl._timeChart.changeData(values);
                                }
                                if (PageControl._rateChart != null) {
                                    PageControl._rateChart.changeData(fxs, fys);
                                }
                            }
//							addLog("完成振动测量");
                        } else if (msg.arg1 == 0xD3) {
                            byte[] data = (byte[]) msg.obj;
                            float rpm = 0;
                            synchronized (_analysis) {
                                int result = _analysis.getDataFromBLE(data, (byte) msg.arg1);
                                if (result == 0) {
                                    rpm = _analysis.getZhuanSu(); //转速
                                    //2019-02-16 chupengyu start
                                    startSendBroadcast(Keys.RPM_ACTION, Keys.rpmKey, String.valueOf(rpm));    //开启广播传输转速值
                                    //end

                                } else {
                                    addLog("0xD3:" + result);
                                    return;
                                }
                            }
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_RPM, rpm);
//							addLog("完成转速测量");
                        } else if (msg.arg1 == 0xD6) {
                            byte[] data = (byte[]) msg.obj;
                            double temp = 0.0f;
                            double voltage = 0.0f;
                            DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
                            synchronized (_analysis) {
//								fashelv=getmEmissivity((Float)CacheControl.GetInstance().get(CacheControl.Key_Value_Txt_Default_E));
                                fashelv = (Float) CacheControl.GetInstance().get(CacheControl.Key_Value_Txt_Default_E);
//								Log.e("MainActivity", "Emissivity="+fashelv);
                                int result = _analysis.getDataFromBLE(data, (byte) msg.arg1);
                                if (result == 0) {
//									temp = _analysis.getTemperature();
                                    voltage = _analysis.getTemperature(fashelv)[0];
//									temp = _analysis.getTemperature(fashelv)[1];
                                    temp = Double.parseDouble(df.format(_analysis.getTemperature(fashelv)[1])); //温度
                                    //2019-02-16 chupengyu start
                                    startSendBroadcast(Keys.TEMP_ACTION, Keys.tempKey, String.valueOf(temp));    //开始发送广播传输温度值
                                    //end
                                    if (temp >= 300 || temp <= -20) {
                                        ToastUtil.showToast(getBaseContext(), "超出传感器测量范围");
                                    }
                                } else {
                                    addLog("0xD6:" + result);
                                    return;
                                }
                            }
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Voltage, voltage);
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Temperature, temp);
//							addLog("温度");
                        } else if (msg.arg1 == 0xD7) {
                            byte[] data = (byte[]) msg.obj;
                            int value = HexUtil.getInt(data, 3);
                            double power = (double) value * 2 / (double) 1000;
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Power, power);
                            if (power <= 3.4){
                                sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_LOWPOWER).putExtra("lowpower", "蓝牙设备电量过低，建议自动断开连接并充电"));
                            }
                            sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_POWER).putExtra("power", power+""));

                            long powerPercent = Math.round((power-3.35)/(4.1-3.35)*100);
                            if (powerPercent <= 0 ){
                                sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_POWERPERCENT).putExtra("powerpercent", "0%"));
                            }else{
                                sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_POWERPERCENT).putExtra("powerpercent", powerPercent+"%"));
                            }

//							addLog("电量");
                        }
                    } else {
                        addLog("错误：请求数据超时(" + HexUtil.toHexString(new byte[]{(byte) msg.arg1}) + "),接收包数：" + String.valueOf(msg.arg2));
                    }

                } else if (msg.what == Constants.HANDLER_MEASUREMENT_STARTED) {
                    if (msg.arg1 == 1) {
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Running_Status, false);
//                        setControlStatus(false);
                        ToastUtil.showToast(getBaseContext(), "开始成功，请滑动Tab页面查看数据");
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_START_STATUS).putExtra("status","true"));
                    } else {
                        ToastUtil.showToast(getBaseContext(), "开始失败，请选择正确的传感器设备");
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_START_STATUS).putExtra("status","false"));
                    }
                } else if (msg.what == Constants.HANDLER_IOCONTROL_SETNAME) {
                    BluetoothManager bm = (BluetoothManager) getBaseContext().getSystemService(Context.BLUETOOTH_SERVICE);
                    if (bm != null) {
                        bm.getAdapter().disable();
                    }
//                    if (_waitingDialog != null) {
//                        _waitingDialog.dismiss();
//                    }
                    if (msg.arg1 == 1) {
                        ToastUtil.showToast(getBaseContext(), "设置名称成功");
                        addLog("信息：设置名称成功：" + (String) msg.obj);
                    } else {
                        ToastUtil.showToast(getBaseContext(), "设置名称失败");
                        addLog("错误：设置名称失败：" + (String) msg.obj);
                    }
                    if (bm != null) {
                        bm.getAdapter().enable();
                    }
                }

                // 来自SDK的事件
                else if (msg.what == HandlerConstants.HANDLER_NEW_DEVICE_DISCOVERED) {
                    @SuppressWarnings("unchecked")
                    ArrayAdapter<String> adapter = (ArrayAdapter<String>) CacheControl.GetInstance().get(CacheControl.Key_AvailableSensor);
                    Sensor sensor = (Sensor) msg.obj;
                    String fullname = StringUtil.concat(sensor.Name, "[", sensor.MAC, "]");
                    if (adapter.getPosition(fullname) == -1) {
                        adapter.add(fullname);
                    }
                    sendBroadcast(new Intent(SEND_BLUETOOTH_VALUE).putExtra("name", fullname));
                } else if (msg.what == HandlerConstants.HANDLER_ERROR) {
                    addLog("错误：" + (String) msg.obj);
                } else if (msg.what == HandlerConstants.HANDLER_DEVICE_DISCOVER_COMPLETED) {
                    ToastUtil.showToast(getBaseContext(), "传感器搜索结束");
                } else if (msg.what == HandlerConstants.HANDLER_DEVICE_DISCONNECT) {
                    synchronized (_lock) {
                        if (_requestor != null) {
                            _requestor.cancel();
                            _requestor = null;
                        }
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Running_Status, true);
//                        setControlStatus(true);
                    }
                    ToastUtil.showToast(getBaseContext(), "与传感器断开了连接，测量停止，请重新开始测量");
                    addLog("信息：与传感器断开了连接，测量停止，请重新开始测量");

                } else if (msg.what == Constants.HANDLER_REWRITE_CALIBRATION_CURVE) {
                    String notice = "";
                    try {
                        refreshCalibrationNotice();
                        if (msg.arg1 == 1) //写入校准数据成功
                        {
//							synchronized (PageControl._lock) {
//								Object values = CacheControl.GetInstance().get(CacheControl.Key_Calibration_Chart);
//								if (values != null && PageControl._temp_Curve_Chart != null) {
//									CurveValuePair p = (CurveValuePair) values;
//									PageControl._temp_Curve_Chart.changeData(p.xValue, p.yValue);
//								}
//							}
                            String ble = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Sensor_Name_Address));
                            String BLEMac = ble.substring(ble.indexOf("[") + 1, ble.indexOf("]")).replace(":", "");
//							Setting setting=new Setting();
                            String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
                            String filename = BLEMac + "-temp.txt";
                            if (SystemUtil.isFileExist(path, filename)) {
                                String curve = ReceivedDataAnalysis.getTemperatureCurve(filename);
                                if (ReceivedDataAnalysis.getCalibrationCurvePiontsValue(curve)) {
                                    CurveValuePair valuePair = (CurveValuePair) CacheControl.GetInstance().get(CacheControl.Key_Calibration_Chart);
                                    synchronized (PageControl._lock) {
                                        if (PageControl._temp_Curve_Chart != null) {
                                            PageControl._temp_Curve_Chart.changeData(valuePair.xValue, valuePair.yValue);
                                        }
                                    }
                                }
                            }
                            notice = (String) msg.obj + "。已停止测量，重新开始测量将加载新校准曲线";
                        } else {
                            notice = (String) msg.obj + "。已停止测量";
                        }
//						ToastUtil.showToast(getBaseContext(), (String)msg.obj);
                    } catch (Exception e) {
                        notice = "写入过程出现异常:" + e.getMessage();
                    } finally {
//                        if (_waitingDialog!=null)
//                        {
//                            _waitingDialog.dismiss();
//                        }
                        stopBluetoothMeasurment("停止", "校准完毕，正在停止测量，请稍后……", notice, 0);

                    }

                } else if (msg.what == Constants.HANDLER_BLUETOOTH_PAUSED) {
//					new Thread() {
//						@Override
//						public void run() {
                    addLog("HANDLER_BLUETOOTH_PAUSED");
                    int allowdifferencevalue = CommonDef.TempuratureAllowDifferenceValue;
                    double measurementvalue = Double.parseDouble(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Value_Temperature)));//蓝牙实时测量到的温度值
                    int calibrationvalue = Integer.parseInt(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Value)));//当前应校准的温度
                    if (Math.abs(measurementvalue - calibrationvalue) > allowdifferencevalue)//如果测量值和应校准值相差比较大，可能是黑体箱温度与用户想校准的温度不是一个点，给用户一个提示，是否要强行校准
                    {

                    } else {
                        rewriteCurveCalibration();
                    }
//						}
//					}.start();

                } else if (msg.what == Constants.HANDLER_CALIBRATION_CURVE_ERROR) {
//                    if (_waitingDialog != null) {
//                        _waitingDialog.dismiss();
//                    }
                    ToastUtil.showToast(getApplicationContext(), (String) msg.obj);
                    addLog((String) msg.obj);
                } else if (msg.what == Constants.HANDLER_BLUETOOTH_MEASURE_STOP) {
                    synchronized (_lock) {
//                        if (_waitingDialog != null) {
//                            _waitingDialog.dismiss();
//                        }
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Running_Status, true);
//                        setControlStatus(true);
                        if (msg.arg2 == 1) {
                            writeCalibrationFile();
                        } else {
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_RPM, 0);
//                            restoreTextViewValue(R.id.txt_rpm, CacheControl.Key_Value_RPM);
                            ToastUtil.showToast(getBaseContext(), (String) msg.obj);
                        }
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_STOP_STATUS).putExtra("status","true"));
                    }
                } else if (msg.what == Constants.HANDLER_READY_TO_REWRITE_CALIBRATION) {
                    rewriteCurveCalibration();
                } else if (msg.what == Constants.HANDLER_CHECK_CALIBRATION_CURVE) {
                    addLog((String) msg.obj);
                    ToastUtil.showToast(getBaseContext(), "曲线检测完毕，请查看日志");
                }
            } catch (Exception e) {
                LogUtil.GetInstance().append(e);
            }
        }
    };

    private void writeCalibrationFile() {
        String sensorname = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Sensor_Name_Address));
        if (StringUtil.isNullOrWhiteSpace(sensorname)) {
            _handler.obtainMessage(Constants.HANDLER_CALIBRATION_CURVE_ERROR, 0, 0, "请选中传感器，再校准温度曲线").sendToTarget();
            return;
        }
        int allowdifferencevalue = CommonDef.TempuratureAllowDifferenceValue;
        double measurementvalue = Double.parseDouble(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Value_Temperature)));//蓝牙实时测量到的温度值
        if ((int) measurementvalue == CommonDef.InvalidValue) {
            _handler.obtainMessage(Constants.HANDLER_CALIBRATION_CURVE_ERROR, 0, 0, "测量温度不准确，请确认是否已经开始测量").sendToTarget();
            return;
        }
        int calibrationvalue = Integer.parseInt(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Value)));//当前应校准的温度
        if (Math.abs(measurementvalue - calibrationvalue) > allowdifferencevalue)//如果测量值和应校准值相差比较大，可能是黑体箱温度与用户想校准的温度不是一个点，给用户一个提示，是否要强行校准
        {
//            showForceCalibrationDialog();
        } else {
            rewriteCurveCalibration();
        }
    }

    private void rewriteCurveCalibration() {
//        _waitingDialog = ProgressDialog.show(MainActivity.this, "写入校准值", "请勿挪动传感器及更改黑体箱温度！更新校准值，请稍后…");
//        _waitingDialog.setCancelable(true);
        new Thread() {
            @Override
            public void run() {
                try {
                    addLog("rewriteCurveCalibration");
                    String sensorname = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Sensor_Name_Address));
                    String BLEAddress = sensorname.substring(sensorname.indexOf("[") + 1, sensorname.indexOf("]"));
                    String BLEMac = BLEAddress.replace(":", "");
                    String BLECurveName = BLEMac + "-temp.txt";

                    int calibrationindex = Integer.parseInt(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Index)));//当前应校准的温度索引
                    double xValue = Double.parseDouble(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Voltage)));//蓝牙实时测量到的温度值换算之前的电压值
                    double yValue = Double.parseDouble(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Value)));//当前应校准的温度
//					xValue=1107;//测试用
//					yValue=20;//测试用
                    String curve = ReceivedDataAnalysis.getTemperatureCurve(BLECurveName);//获取当前蓝牙对应的温度曲线内容，如果不存在，则获取默认文件的曲线内容
                    if (ReceivedDataAnalysis.getCalibrationTotalPoints() != (ReceivedDataAnalysis.getCurveTotalPoints(curve) - 1)) //目前校准时，有一个点是低于-20度的，只不过该点不用校准，因此不显示给用户看
                    {
                        //校准的基准曲线上的基准点数与校准标准点数不一致
                        _handler.obtainMessage(Constants.HANDLER_REWRITE_CALIBRATION_CURVE, 0, 0, "禁止写入校准数据:" + "应校准点数与当前设备已有校准曲线文件包含的点数不一致，请删除当前设备校准曲线文件或重设温度校准范围及步进值").sendToTarget();
                        return;
                    } else {
                        ReceivedDataAnalysis.UpdateCurve(getApplicationContext(), curve, xValue, yValue, calibrationindex, BLEMac);
                        _handler.obtainMessage(Constants.HANDLER_REWRITE_CALIBRATION_CURVE, 1, 0, "写入校准数据成功").sendToTarget();
                    }

                } catch (Exception e) {
                    _handler.obtainMessage(Constants.HANDLER_REWRITE_CALIBRATION_CURVE, 0, 0, "写入校准数据失败:" + e.getMessage()).sendToTarget();
                }

            }
        }.start();
    }

    /**
     * 开启广播，传输数据
     *
     * @param action intent的actiong名称
     * @param key
     * @param val
     */
    private void startSendBroadcast(String action, String key, String val) {
        Intent mIntent = new Intent();
        mIntent.setAction(action);
        mIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        Bundle bundle = new Bundle();
        bundle.putString(key, val);
        mIntent.putExtras(bundle);
        sendBroadcast(mIntent);
    }

    private List<BluetoothRequest> makeRequests() {
        boolean flag = false;
        try {
            flag = (Boolean) CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration);
        } catch (Exception e) {
            flag = false;
        }
        List<BluetoothRequest> requests = new ArrayList<BluetoothRequest>();
        // D1
        byte[] data = new byte[]{(byte) 0x7F, (byte) 0x14, (byte) 0xD1, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};

        data[3] = (byte) (1);
        data[4] = (byte) (2);
        short sr = 2560;
        data[5] = (byte) ((sr & 0xff00) >> 8);
        data[6] = (byte) (sr & 0xff);
        short sp = 1024;
        int totallen = 2 * sp + 40;
        data[7] = (byte) ((sp & 0xff00) >> 8);
        data[8] = (byte) (sp & 0xff);

        int timeout = Constants.EveryPackageDelay * (sp * 2 / Constants.EveryPackageLen) + (short) (1000.0 * (float) sp / (float) sr) + 6200;
        if (flag) {
            data = new byte[]{(byte) 0x7F, (byte) 0x14, (byte) 0xD6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
            BluetoothRequest r = new BluetoothRequest(0xD6, data, 20, null, 4000);
            requests.add(r);
        } else {
            BluetoothRequest r = new BluetoothRequest(0xD1, data, totallen, null, timeout);
            requests.add(r);

            boolean flag_rpm = false;
            try {
                flag_rpm = (Boolean) CacheControl.GetInstance().get(CacheControl.Key_Enable_RPM);
            } catch (Exception e) {
                flag_rpm = false;
            }
            if (flag_rpm) {
                data = new byte[]{(byte) 0x7F, (byte) 0x14, (byte) 0xD3, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};

//				r = new BluetoothRequest(0xD3, data, 20, null, 4000);//2016-12-24 liuhg修改前原程序
                r = new BluetoothRequest(0xD3, data, 20, null, 10000);//2016-12-24 liuhg修改  最低转速时 超时设置延长到10s
                requests.add(r);
            }

            data = new byte[]{(byte) 0x7F, (byte) 0x14, (byte) 0xD6, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};

            r = new BluetoothRequest(0xD6, data, 20, null, 4000);
            requests.add(r);

            data = new byte[]{(byte) 0x7F, (byte) 0x14, (byte) 0xD7, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};

            r = new BluetoothRequest(0xD7, data, 20, null, 4000);
            requests.add(r);
        }
        return requests;
    }

    private void refreshCalibrationNotice() {
        String noticerange = ReceivedDataAnalysis.getTempCalRange();
        String noticestep = ReceivedDataAnalysis.getTempCalStep();
        String noticeschedule = "";
        String pointvalue = "";
        String pointindex = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Index));
        String name = (String) CacheControl.GetInstance().get(CacheControl.Key_Sensor_Name_Address);
        if (StringUtil.isNullOrWhiteSpace(name)) {
            pointindex = "0";
        }
//		noticeschedule=pointindex+"/"+String.valueOf(ReceivedDataAnalysis.getCalibrationTotalPoints());
        if (Integer.parseInt(pointindex) == ReceivedDataAnalysis.getCalibrationTotalPoints()) {
            noticeschedule = pointindex + "/" + String.valueOf(ReceivedDataAnalysis.getCalibrationTotalPoints()) + CommonDef.TempuratureCalbFinish;
            pointvalue = String.valueOf(ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(pointindex) - 1));
        } else {
            noticeschedule = pointindex + "/" + String.valueOf(ReceivedDataAnalysis.getCalibrationTotalPoints());
            pointvalue = String.valueOf(ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(pointindex)));
        }
//		String pointvalue=String.valueOf(ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(pointindex)));
        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Schedule, noticeschedule);
        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Range, noticerange);
        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Step, noticestep);
        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Value, pointvalue);


    }

    /**
     * @param title  进度条标题
     * @param cue    进度条内容
     * @param notice 停止成功之后给用户的提示
     * @param flag   =0,只停止测量；=1.停止测量之后，进行校准参数更新
     */
    public void stopBluetoothMeasurment(String title, String cue, final String notice, final int flag) {
        synchronized (_lock) {
//            _waitingDialog = ProgressDialog.show(MainActivity.this, title,cue);
//            _waitingDialog.setCancelable(true);
            try {
                new Thread() {
                    @Override
                    public void run() {
                        if (_requestor != null) {
                            _requestor.cancel();
                            _requestor = null;
                        }
                        _handler.obtainMessage(Constants.HANDLER_BLUETOOTH_MEASURE_STOP, 1, flag, notice).sendToTarget();
                    }
                }.start();
            } catch (Exception e) {
                _handler.obtainMessage(Constants.HANDLER_BLUETOOTH_MEASURE_STOP, 0, flag, "stopBluetoothMeasurment出现异常:" + e.getMessage()).sendToTarget();
                sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_STOP_STATUS).putExtra("status","false"));
            }
        }
    }


    private class BlueToothReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case BluetoothDevice.ACTION_ACL_CONNECTED:
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_CONNECT));
//                        Toast.makeText(context, "蓝牙设备已连接", Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                        sendBroadcast(new Intent(COM_AICMONITOR_AICDETACTORSIMPLE_CONTROL_BLUETOOTH_DISCONNECT));
//                        Toast.makeText(context, "蓝牙设备已断开", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

        }
    }

    @Override
    public void onDestroy() {
        if (controlReceiver != null){
            unregisterReceiver(controlReceiver);
        }
//        if (intent != null)
//            getApplicationContext().stopService(intent);	//2019-02-16 chupengyu修改，停止广播服务
        if (blueToothReceiver != null){
            unregisterReceiver(blueToothReceiver);
        }
        super.onDestroy();
    }

    public static void addLog(String content) {
        Log.e("zxh", content);
    }
}
